﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EnvDTE;
using Microsoft.VisualStudio.CommandBars;
using Microsoft.VisualStudio.Shell;

namespace Utility
{
    public static class EnvDteUtil
    {
        private static readonly string MsbuildMenuCaption = "MSBuild Menu";
        private static readonly string CompileButtonCaption = "Compile Inline Code";

        public static CommandBarButton GetMSBuildCommandBarButton(SVsServiceProvider serviceProvider)
        {
            DTE dte = GetDte(serviceProvider);
            CommandBars cmdBars = (CommandBars)dte.CommandBars;
            CommandBar codeWindowCmdBar = cmdBars["Code Window"];
            
            //Msbuild Menu
            bool isExistMsbuildMenu = false;
            CommandBarPopup msbuildMenu = null;
            foreach (CommandBarControl cbc in codeWindowCmdBar.Controls)
            {
                if (cbc.Caption == MsbuildMenuCaption)
                {
                    isExistMsbuildMenu = true;
                    msbuildMenu = (CommandBarPopup)cbc;
                    break;
                }
            }
            if (!isExistMsbuildMenu)
            {
                msbuildMenu = (CommandBarPopup)codeWindowCmdBar.Controls.Add(
                    MsoControlType.msoControlPopup, 1, Type.Missing, 1, Type.Missing);
                msbuildMenu.Caption = MsbuildMenuCaption;
            }

            //Compile Inline Code
            bool isExistCompileButton = false;
            CommandBarButton compileButton = null;
            foreach (CommandBarControl cbc in msbuildMenu.Controls)
            {
                if (cbc.Caption == CompileButtonCaption)
                {
                    isExistCompileButton = true;
                    compileButton = (CommandBarButton)cbc;
                    break;
                }
            }
            if (!isExistCompileButton)
            {
                compileButton = (CommandBarButton)msbuildMenu.Controls.Add(
                    MsoControlType.msoControlButton, 1, Type.Missing, 1, Type.Missing);
                compileButton.Caption = CompileButtonCaption;
            }

            return compileButton;
        }

        public static DTE GetDte(SVsServiceProvider serviceProvider)
        {
            DTE dte = (DTE)serviceProvider.GetService(typeof(DTE));
            return dte;
        }
    }
}
